import { DoType, getDoTypeTitle } from '@/interfaces'
import { defineComponent, reactive } from 'vue'
import { MenuButtonState, MenuState, columns, updateNodeInTree } from './uilts'
import { FormConfig } from '@/components'
import { clone, equals, isNil, update } from 'ramda'
import { deleteData, errorTips, successTips } from '@/utils'
import CreateIndex from './components/createIndex'
import { isTrue } from '@/utils/tools'

export default defineComponent({
    setup() {
        const rules = {
            name: [{ required: true, message: '请输入中文名称', trigger: 'change' }],
            path: [{ required: true, message: '请输入路由地址', trigger: 'change' }],
            sort: [{ required: true, type: 'number', message: '请输入排序值', trigger: 'change' }],
            route: [{ required: true, message: '请输入路由别名', trigger: 'change' }],
            description: [{ required: true, message: '请输入功能描述', trigger: 'change' }],
            type: [{ required: true, type: 'number', message: '请选择页面类型', trigger: 'change' }],
            is_use: [{ required: true, type: 'number', message: '请选择是否可用', trigger: 'change' }],
            is_navbar: [{ required: true, type: 'number', message: '请选择是否导航栏显示', trigger: 'change' }],
        }
        const pageState = reactive({
            visible: false,
            formData: {} as MenuState,
            type: DoType.create,
            buttons: {},
            loading: false,
            dataSource: [] as any[],
            selectedKeys: [],
            expandedKeys: [] as number[],
        })
        getMeun()
        async function getMeun() {
            pageState.selectedKeys = []
            const { success, data } = await API.server.menu.getMenuTree.request()
            if (success) {
                pageState.dataSource = [
                    {
                        id: 0,
                        parentId: 0,
                        name: '全部',
                        type: 1,
                        sort: 0,
                        is_use: 1,
                        is_navbar: 1,
                        children: data
                    }
                ]
                pageState.expandedKeys = [0]
            }
        }
        // 定义递归函数，将对象中的 child 转换为数组
        function convertChildToArray(obj: any) {
            if (obj.children && Object.keys(obj.children).length > 0) {
                obj.children = Object.values(obj.children).map(convertChildToArray);
            }
            return obj;
        }
        async function submit() {
            if (equals(pageState.formData.id, 0)) {
                errorTips('无法编辑')
                return
            }
            const params = {
                id: pageState.formData.id as number,
                name: pageState.formData.name as string,
                parentId: pageState.formData.parentId,
                type: pageState.formData.type as 1 | 2,
                sort: pageState.formData.sort as number,
                is_use: pageState.formData.is_use as 1 | 2,
                is_navbar: pageState.formData.is_navbar as 1 | 2,
                path: pageState.formData.path as string,
                route: pageState.formData.route as string,
                description: pageState.formData.description as string,
            }
            if (equals(params.parentId, 0)) {
                delete params.parentId
            }
            const func = equals(pageState.type, DoType.create)
                ? API.server.menu.createMenu.request
                : API.server.menu.updateMenu.request
            pageState.loading = true
            const { success, msg, data } = await func(params)
            pageState.loading = false
            if (success) {
                successTips(`${getDoTypeTitle(pageState.type)}成功`)
                getMeun()
                if (equals(pageState.type, DoType.create)) {
                    pageState.formData = data
                }
                pageState.type = DoType.create
                return
            }
            errorTips(msg)
        }

        function actionRender({ record }: F.RableSlotScope<MenuState>) {
            return (
                <a-space size="middle">
                    <a-button
                        type="link"
                        block
                        v-auth="edit"
                        onClick={() => {
                            pageState.buttons = clone(record)
                            pageState.type = DoType.edit
                            pageState.visible = true
                        }}
                    >
                        编辑
                    </a-button>
                    <a-button v-auth="del" type="link" block danger onClick={() => deleteData({ id: record.id }, API.server.menu.deleteMenu.request, () => {
                        getMeun()
                        pageState.formData = {}
                    })}>
                        删除
                    </a-button>
                </a-space>
            )
        }
        /** 更新菜单按钮 */
        function updateMenuButton(data: MenuButtonState) {
            const index = pageState.formData.menuButton?.findIndex(item => equals(item.id, data.id)) ?? -1
            if (index === -1) {
                pageState.formData.menuButton?.push(data)
            } else {
                pageState.formData.menuButton && (pageState.formData.menuButton[index] = data)
            }
            updateNodeInTree(pageState.dataSource, pageState.formData.id, pageState.formData)
        }
        return () => <div>
            <div style="background: #fff;padding: 10px;margin: 0 0 10px">
                <a-button
                    type="primary"
                    v-auth="add"
                    onClick={() => {
                        if (equals(pageState.formData?.type, 2)) {
                            errorTips('页面类型无法进行添加')
                            return
                        }
                        pageState.type = DoType.create
                        pageState.formData = {
                            parentId: pageState.formData.id ?? 0
                        }
                    }}
                >
                    新增
                </a-button>
            </div>
            <a-row>
                <a-col span={5} style="padding-right: 10px">
                    <a-card title="菜单列表" style="border-radius: 6px;">
                        <a-tree
                            tree-data={pageState.dataSource}
                            v-models={[[pageState.expandedKeys, 'expandedKeys'], [pageState.selectedKeys, 'selectedKeys']]}
                            replaceFields={{
                                children: 'children', title: 'name', key: 'id'
                            }}
                            onSelect={(data: number[], { selectedNodes }: any) => {
                                pageState.formData = clone(selectedNodes[0].props)
                                pageState.type = DoType.edit
                            }}
                        >
                        </a-tree>
                    </a-card>
                </a-col>
                <a-col span={19}>
                    <a-form
                        class="ant-advanced-search-form"
                        labelCol={{ span: 8 }}
                        wrapperCol={{ span: 14 }}
                        model={pageState.formData}
                        rules={rules}
                        onFinish={submit}
                    >
                        <a-card title="基础信息" style="border-radius: 6px;margin: 0 0 10px" v-slots={{
                            extra: () => (
                                <a-button type="link" v-auth="del" block danger disabled={isNil(pageState.formData.id) || equals(pageState.formData.id, 0)} onClick={() => {
                                    if (isNil(pageState.formData.id)) {
                                        errorTips('删除失败，id不存在')
                                        return
                                    }
                                    deleteData({ id: pageState.formData.id }, API.server.menu.deleteMenu.request, () => {
                                        getMeun()
                                        pageState.formData = {}
                                    })
                                }}>
                                    删除
                                </a-button>
                            )
                        }}>
                            <a-row>
                                <a-col span={8}>
                                    <a-form-item name="name" label="中文名称">
                                        <a-input v-model={[pageState.formData.name, 'value']} />
                                    </a-form-item>
                                </a-col>
                                <a-col span={8}>
                                    <a-form-item name="type" label="类型">
                                        <FormConfig prop="pageType" v-model={[pageState.formData.type, 'value']} disabled={equals(pageState.type, DoType.edit)} />
                                    </a-form-item>
                                </a-col>
                                <a-col span={8}>
                                    <a-form-item name="sort" label="排序">
                                        <a-input-number min={0} v-model={[pageState.formData.sort, 'value']} />
                                    </a-form-item>
                                </a-col>
                                <a-col span={8}>
                                    <a-form-item name="is_use" label="是否可用">
                                        <FormConfig prop="flag1" v-model={[pageState.formData.is_use, 'value']} />
                                    </a-form-item>
                                </a-col>
                                <a-col span={8}>
                                    <a-form-item name="is_navbar" label="是否在导航栏显示">
                                        <FormConfig prop="flag1" v-model={[pageState.formData.is_navbar, 'value']} />
                                    </a-form-item>
                                </a-col>
                                <a-col span={8}>
                                    <a-form-item name="path" label="路由地址">
                                        <a-input v-model={[pageState.formData.path, 'value']} />
                                    </a-form-item>
                                </a-col>
                                <a-col span={8}>
                                    <a-form-item name="route" label="路由别名">
                                        <a-input v-model={[pageState.formData.route, 'value']} />
                                    </a-form-item>
                                </a-col>
                                <a-col span={8}>
                                    <a-form-item name="description" label="功能描述">
                                        <a-textarea v-model={[pageState.formData.description, 'value']} rows={2} />
                                    </a-form-item>
                                </a-col>
                            </a-row>

                        </a-card>
                        {
                            equals(pageState.formData.type, 2) && isTrue(pageState.formData.id) && (
                                <a-card title="按钮信息" style="border-radius: 6px;" v-slots={{
                                    extra: () => (
                                        <a-button
                                            type="primary"
                                            v-auth="add"
                                            onClick={() => {
                                                pageState.visible = true
                                                pageState.buttons = {}
                                            }}
                                        >
                                            新增
                                        </a-button>
                                    )
                                }}>
                                    <a-table v-slots={{ actionRender }} dataSource={pageState.formData.menuButton ?? []} columns={columns} pagination={false}></a-table>
                                </a-card>
                            )
                        }
                        <div style="text-align: center;margin: 20px 0 0">
                            <a-button
                                type="primary"
                                html-type="submit"
                                v-auth="save"
                            >
                                保存
                            </a-button>
                        </div>
                    </a-form>
                </a-col>
            </a-row>
            <CreateIndex
                visible={pageState.visible}
                menuId={pageState.formData?.id as number}
                dataSource={pageState.buttons}
                onSubmit={updateMenuButton}
                onCancel={() => {
                    pageState.visible = false
                    pageState.buttons = {}
                }}
            />
        </div >
    }
})